//
//  PublicUtil.m
//  test
//
//  Created by 袁应荣 on 2017/3/11.
//  Copyright © 2017年 袁应荣. All rights reserved.
//

#import "PublicUtil.h"
#import <ifaddrs.h>
#import <arpa/inet.h>

@implementation PublicUtil

+ (NSString *)formatFloatNum:(double)num {
    
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"###,##0.00;"];
    NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:num]];
    
    return formattedNumberString;
}


// Get IP Address
+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}


#pragma mark -- 字典转JSON
//NSJSONWritingPrettyPrinted  是有换位符的。
//如果NSJSONWritingPrettyPrinted 是nil 的话 返回的数据是没有换位符的
+ (NSString*)dictionaryToJson:(NSDictionary *)dic {
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

#pragma mark -- 字符串尺寸
+ (CGSize)SizeForString:(NSString *)str WithFont:(UIFont *)font AndWidth:(NSInteger)width {
    if (!str) {
        return CGSizeZero;
    }

    NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:str attributes:attrsDictionary];
    
    CGRect paragraphRect =
    [attributedText boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                 options:(NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                 context:nil];
    CGSize returnSize = CGSizeMake(ceilf(paragraphRect.size.width), ceilf(paragraphRect.size.height));
    
    return returnSize;
}


//  NSAttributedString 专用
+ (CGFloat)heightForLabelWithNSAttributedString:(NSAttributedString *)attrStr labelWidth:(CGFloat)labelWidth {
    CGFloat titleHeight;
    
    NSStringDrawingOptions options =  NSStringDrawingUsesLineFragmentOrigin;
    CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX)
                                        options:options
                                        context:nil];
    titleHeight = ceilf(rect.size.height);
    
    return titleHeight+2;  // 加两个像素,防止emoji被切掉.
}

// 计算 普通text 对应的高度
+ (CGFloat)heightForCellWithText:(NSString *)contentText fontSize:(UIFont *)labelFont labelWidth:(CGFloat)labelWidth {
    CGFloat titleHeight = 0;
    if ([contentText length]) {
        NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:contentText
                                                                             attributes:@{ NSFontAttributeName:labelFont}];
        titleHeight = [self heightForLabelWithNSAttributedString:attributedText labelWidth:labelWidth];
    }
    
    return titleHeight;
}


+ (NSAttributedString *)getMutableStringWithStr:(NSString *)str withLineSpace:(NSInteger )space {
    /**调整label的行间距*/
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    
    //    lb_content.attributedText = [self getMutableStringWithStr:spec.content withLineSpace:4];
    //    [lb_content sizeToFit];
    
    return attributedString;
}

+ (NSAttributedString *)GetMutableStringWithStr:(NSMutableAttributedString *)str withLineSpace:(NSInteger )space {

    /**调整label的行间距*/
//    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    
    //    lb_content.attributedText = [self getMutableStringWithStr:spec.content withLineSpace:4];
    //    [lb_content sizeToFit];
    
    return str;
    
}

#pragma mark - Date 相关

+ (NSDate *)getNSDateFromString:(NSString *)dateStr {
    //
    //    CST -06:00 美国中部标准时间
    //    CCT +08:00 中国标准时间
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];   //实例化一个NSDateFormatter对象
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];  //设定时间格式,这里可以设置成自己需要的格式
    //    NSDate *date =[dateFormat dateFromString:@"1980-01-01 00:00:01"];
    
    NSDate *destDate =[dateFormat dateFromString:dateStr];
    
    return destDate;
}

// 根据日期返回NSDate对象(日期格式: 2014-01-02)
+ (NSDate *)getNSDateFromSimpleDateString:(NSString *)dateStr {
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];   //实例化一个NSDateFormatter对象
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];  //设定时间格式,这里可以设置成自己需要的格式
    NSDate *destDate =[dateFormat dateFromString:dateStr];
    
    return destDate;
}

// 根据NSDate返回String对象(格式: 2014.01.02)
+ (NSString *)getStringFromPointDate:(NSDate *)destDate {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy.MM.dd"];
    
    return [dateFormatter stringFromDate:destDate];
}

// 根据NSDate返回String对象(格式: 2014/01/02)
+ (NSString *)getStringFromNSDate:(NSDate *)destDate {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    
    return [dateFormatter stringFromDate:destDate];
}


+ (NSString *)getChineseWeekdayWithDateString:(NSString *)dateStr {
    NSString *weekStr = nil;
    NSDate *destDate = [self getNSDateFromString:dateStr];
    
    if (!destDate) {
        NSLog(@"NIL ERROR!");
        return @"";
    }
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSInteger unitFlags = NSCalendarUnitWeekday | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:destDate];
    
    NSInteger week = [comps weekday];
    NSInteger month = [comps month];
    NSInteger day = [comps day];
    
    if(week==1) {
        weekStr=@"周日";
    } else if(week==2) {
        weekStr=@"周一";
        
    } else if(week==3) {
        weekStr=@"周二";
        
    } else if(week==4) {
        weekStr=@"周三";
        
    } else if(week==5) {
        weekStr=@"周四";
        
    } else if(week==6) {
        weekStr=@"周五";
        
    } else if(week==7) {
        weekStr=@"周六";
    } else {
        NSLog(@"error!");
    }
    
    NSString *destStr = [NSString stringWithFormat:@"%@  %ld月%ld日", weekStr, (long)month, (long)day];
    
    return destStr;
}

+ (NSString *)getTimeStrWithString:(NSString *)dateStr {
    NSDate *destDate = [self getNSDateFromString:dateStr];
    if (!destDate) {
        NSLog(@"NIL ERROR!");
        return @"";
    }
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSInteger unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:destDate];
    
    NSInteger hour = [comps hour];
    NSInteger minute = [comps minute];
    
    NSString *destStr = [NSString stringWithFormat:@"%02ld:%02ld", (long)hour, (long)minute];
    
    return destStr;
}

+ (NSString *)getTimeStrWithString:(NSString *)dateStr FormatterStr:(NSString *)fStr {
    NSDate *destDate = [self getNSDateFromString:dateStr];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    if (fStr) {
        [dateFormatter setDateFormat:fStr];
    } else {
        [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    }
    
    return [dateFormatter stringFromDate:destDate];
}

#pragma mark -- 获取某个月的天数
+ (NSInteger)getSumOfDaysInMonth:(NSString *)year month:(NSString *)month {
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM"]; // 年-月
    NSString * dateStr = [NSString stringWithFormat:@"%@-%@",year,month];
    NSDate * date = [formatter dateFromString:dateStr];
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay
                                   inUnit: NSCalendarUnitDay
                                  forDate:date];
    return range.length;
}

#pragma mark - 比较两个日期
+ (int)compareOneDate:(NSDate *)oneDate withAnotherDate:(NSDate *)anotherDate {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDate];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDate];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"date1 : %@, date2 : %@", oneDate, anotherDate);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
}

#pragma mark - 计算两个日期相差的年
+ (NSInteger)calculateFromDate:(NSDate *)fromDate withToDate:(NSDate *)toDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [gregorian setFirstWeekday:2];
    
    NSDateComponents *components = [gregorian components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
    NSInteger year = components.year;
//    NSInteger month = components.month;
//    NSInteger day = components.day;
    return year;
}

+ (NSInteger)calculateFromDateStr:(NSString *)fromDateStr withToDateStr:(NSString *)toDateStr {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [gregorian setFirstWeekday:2];
    NSDate *fromDate = [self getNSDateFromString:fromDateStr];
    NSDate *toDate = [self getNSDateFromString:toDateStr];
    NSDateComponents *components = [gregorian components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
    NSInteger year = components.year;
    //    NSInteger month = components.month;
    //    NSInteger day = components.day;
    return year;
}

+ (NSInteger)calculateDayFromDateStr:(NSString *)fromDateStr withToDateStr:(NSString *)toDateStr {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [gregorian setFirstWeekday:2];
    NSDate *fromDate = [self getNSDateFromString:fromDateStr];
    NSDate *toDate = [self getNSDateFromString:toDateStr];
    NSDate *fromDatea;
    NSDate *toDatea;
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDatea interval:NULL forDate:fromDate];
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDatea interval:NULL forDate:toDate];
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDatea toDate:toDatea options:0];
//     dayComponents.day  // 即为间隔的天数

    return dayComponents.day;
}

#pragma mark -  延时执行

+ (void)doSomething:(void (^)(void))functions
     afterDelayTime:(double)delayInSeconds {
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
                       functions();
                   });
}

+ (void)doSomethingLater:(void (^)(void))functions {
    [self doSomething:functions
               afterDelayTime:0.8];
}

#pragma mark - 主线程执行

+ (void)doSomethingOnMainThread:(void (^)(void))functions {
    dispatch_async(dispatch_get_main_queue(), ^{
        functions();
    });
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0,0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context =UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *img =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

#pragma mark 金币大小写 --> 封装的方法
+ (NSString *)changetoBigMoney:(NSString *)numstr {
    
    // 转化成double类型
    double numberals = [numstr doubleValue];
    
    NSArray *numberchar = @[@"零",@"壹",@"贰",@"叁",@"肆",@"伍",@"陆",@"柒",@"捌",@"玖"];
    
    NSArray *inunitchar = @[@"",@"拾",@"佰",@"仟"];
    
    NSArray *unitname = @[@"",@"万",@"亿",@"万亿"];

    // 金额乘以100转换成字符串（去除圆角分数值）
    NSString *valstr=[NSString stringWithFormat:@"%.2f",numberals];
    
//    NSLog(@"valstr: %@",valstr);

    NSString *prefix;
    
    NSString *suffix;

//    NSLog(@"%lu",(unsigned long)valstr.length);

    if (valstr.length <= 2) {
        
        prefix=@"零元";

        if (valstr.length == 0) {
            
            suffix=@"零角零分";
        } else if (valstr.length == 1) {
            
            suffix=[NSString stringWithFormat:@"%@分",[numberchar objectAtIndex:[valstr intValue]]];
        } else {
            NSString *head = [valstr substringToIndex:1];
            
            NSString *foot = [valstr substringFromIndex:1];
            
            suffix=[NSString stringWithFormat:@"%@角%@分",[numberchar objectAtIndex:[head intValue]],[numberchar objectAtIndex:[foot intValue]]];
            
        }
        
    } else {
        
        prefix=@"";
        
        suffix=@"";
 
        int flag = (int)valstr.length - 2;
        
//        NSLog(@"flag: %d",flag);
 
        NSString *head = [valstr substringToIndex:flag-1];
        
//        NSLog(@"head: %@",head);
 
        NSString *foot = [valstr substringFromIndex:flag];
        
//        NSLog(@"foot: %@",foot);
 
        if (head.length>13) {
            
            return @"数值太大（最大支持13位整数），无法处理";
        }
        
        // 处理整数部分
        NSMutableArray * ch = [[NSMutableArray alloc]init];
        
        for (int i = 0; i < head.length; i++) {
            
//            NSLog(@"head[i]: %hu",[head characterAtIndex:i]);
 
            NSString * str=[NSString stringWithFormat:@"%x",[head characterAtIndex:i]-'0'];
            
            [ch addObject:str];
 
//            NSLog(@"ch: %@",ch);
        }
        
//        NSLog(@"ch_All: %@",ch);
        int zeronum = 0;
        
//        NSLog(@"ch.count: %ld",ch.count);
        
        for (int i = 0; i < ch.count; i++) {
            
            int index = (ch.count - i - 1) % 4; // 取段内位置
            
//            NSLog(@"index: %d",index);
            
            int indexloc = (int)(ch.count - i - 1) / 4; // 取段位置
            
//            NSLog(@"indexloc: %d",indexloc);
//
//            NSLog(@"ch[i]: %@",[ch objectAtIndex:i]);
            
            if ([[ch objectAtIndex:i] isEqualToString:@"0"]) {
                
                zeronum++;
            } else {
                if (zeronum != 0) {
                    
                    if (index != 3) {
                        prefix=[prefix stringByAppendingString:@"零"];
                    }
                     zeronum = 0;
                }
                
                prefix = [prefix stringByAppendingString:[numberchar objectAtIndex:[[ch objectAtIndex:i]intValue]]];
                
                prefix = [prefix stringByAppendingString:[inunitchar objectAtIndex:index]];
                
            }
            
            if (index == 0 && zeronum < 4) {
                
                prefix=[prefix stringByAppendingString:[unitname objectAtIndex:indexloc]];
            }
        }
        
        prefix = [prefix stringByAppendingString:@"元"];
        
        // 处理小数位
        if ([foot isEqualToString:@"00"]) {
            
            suffix =[suffix stringByAppendingString:@"整"];
        }
        
        else if ([foot hasPrefix:@"0"]) {
            
            NSString * footch=[NSString stringWithFormat:@"%x",[foot characterAtIndex:1]-'0'];
            suffix = [NSString stringWithFormat:@"%@分",[numberchar objectAtIndex:[footch intValue]]];
        } else {
            
            NSString * headch=[NSString stringWithFormat:@"%x",[foot characterAtIndex:0]-'0'];
            
            NSString * footch=[NSString stringWithFormat:@"%x",[foot characterAtIndex:1]-'0'];
            suffix = [NSString stringWithFormat:@"%@角%@分",[numberchar objectAtIndex:[headch intValue]],[numberchar objectAtIndex:[footch intValue]]];
        } 
    }
    
    return [prefix stringByAppendingString:suffix];
}

/// 判断字典为空
+ (BOOL)isBlankDictionary:(NSDictionary *)dict {
    if (!dict) {
        return YES;
    }
    if ([dict isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (![dict isKindOfClass:[NSDictionary class]]) {
        return YES;
    }
    if (!dict.count) {
        return YES;
    }
    if (dict == nil) {
        return YES;
    }
    if (dict == NULL) {
        return YES;
    }
    
    return NO;
}

///  判断字符串是否为空
+ (BOOL)isBlankString:(NSString *)aStr {
    if (!aStr) {
        return YES;
    }
    if ([aStr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (!aStr.length) {
        return YES;
    }
    if (aStr == nil) {
        return YES;
    }
    if (aStr == NULL) {
        return YES;
    }
    if ([aStr isEqualToString:@"NULL"]) {
        return YES;
    }
    if ([aStr isEqualToString:@"nil"]) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}

/// 判断数组为空
+ (BOOL)isBlankArr:(NSArray *)arr {
    if (!arr) {
        return YES;
    }
    if ([arr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (![arr isKindOfClass:[NSArray class]]) {
         return YES;
    }
    if (!arr.count) {
        return YES;
    }
    if (arr == nil) {
        return YES;
    }
    if (arr == NULL) {
        return YES;
    }
    
    return NO;
}

/// 保持小数点后两位，不足补小数点或者0.
+ (NSString*)returnTwoDeciTwoDecimalFormatter:(NSString *)stringNumber {
//    stringNumber = [NSString stringWithFormat:@"%@",stringNumber];
    stringNumber = [self returnDecimalFormatterWithStrNum:stringNumber scale:2];
    if([stringNumber rangeOfString:@"."].location == NSNotFound) {
        NSString *string_comp = [NSString stringWithFormat:@"%@.00",stringNumber];
        return string_comp;
    } else {
        NSArray *arrays = [stringNumber componentsSeparatedByString:@"."];
        NSString *s_f = [arrays objectAtIndex:0];NSString* s_e = [arrays objectAtIndex:1];
        if(s_e.length > 2) {
            s_e = [s_e substringWithRange:NSMakeRange(0,2)];
        } else if (s_e.length==1) {
            s_e = [NSString stringWithFormat:@"%@0",s_e];
        }
        NSString *string_combine = [NSString stringWithFormat:@"%@.%@",s_f,s_e];
        return string_combine;
    }
    return @"";
}

/// 保持小数点后两位没有小数位的不添加
+ (NSString *)returnTwoDeciDecimalFormatter:(NSString*)stringNumber {
//    stringNumber =[NSString stringWithFormat:@"%@",stringNumber];
//    if([stringNumber rangeOfString:@"."].location == NSNotFound) {
//        return stringNumber;
//    } else {
//        NSArray *arrays = [stringNumber componentsSeparatedByString:@"."];
//        NSString *s_f = [arrays objectAtIndex:0];NSString* s_e = [arrays objectAtIndex:1];
//        if(s_e.length > 2) {
//            s_e = [s_e substringWithRange:NSMakeRange(0,2)];
//        } else if (s_e.length==1) {
//            s_e = [NSString stringWithFormat:@"%@0",s_e];
//        }
//        NSString *string_combine = [NSString stringWithFormat:@"%@.%@",s_f,s_e];
//        return string_combine;
//    }
//    return @"";
    return [self returnDecimalFormatterWithStrNum:stringNumber scale:2];
}

+ (NSString *)returnDecimalFormatterWithStrNum:(NSString *)StrNum scale:(short)scale {
    NSDecimalNumberHandler *behavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:scale raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *numResult = [NSDecimalNumber decimalNumberWithString:StrNum];
    return [numResult decimalNumberByRoundingAccordingToBehavior:behavior].stringValue;
}

+ (void)yyr_updateWithAPPID:(NSString *)appId withBundleId:(NSString *)bundelId block:(UpdateBlock)block{
    NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
    __block NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];
    NSURLRequest *request;
    if (appId != nil) {
        request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",appId]]];
        NSLog(@"【1】当前为APPID检测，您设置的APPID为:%@  当前版本号为:%@",appId,currentVersion);
    } else if (bundelId != nil){
        request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?bundleId=%@&country=cn",bundelId]]];
        NSLog(@"【1】当前为BundelId检测，您设置的bundelId为:%@  当前版本号为:%@",bundelId,currentVersion);
    } else {
        NSString *currentBundelId=infoDic[@"CFBundleIdentifier"];
        request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?bundleId=%@&country=cn",currentBundelId]]];
        NSLog(@"【1】当前为自动检测检测,  当前版本号为:%@",currentVersion);
    }
    NSURLSession *session = [NSURLSession sharedSession];
    NSLog(@"【2】开始检测...");
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"【3】检测失败，原因：\n%@",error);
            dispatch_async(dispatch_get_main_queue(), ^{
                block(currentVersion,@"",@"",NO);
            });
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if ([appInfoDic[@"resultCount"] integerValue] == 0) {
                NSLog(@"检测出未上架的APP或者查询不到");
                block(currentVersion,@"",@"",NO);
                return;
            }
            NSLog(@"【3】苹果服务器返回的检测结果：\n appId = %@ \n bundleId = %@ \n 开发账号名字 = %@ \n 商店版本号 = %@ \n 应用名称 = %@ \n 打开连接 = %@",appInfoDic[@"results"][0][@"artistId"],appInfoDic[@"results"][0][@"bundleId"],appInfoDic[@"results"][0][@"artistName"],appInfoDic[@"results"][0][@"version"],appInfoDic[@"results"][0][@"trackName"],appInfoDic[@"results"][0][@"trackViewUrl"]);
            NSString *appStoreVersion = appInfoDic[@"results"][0][@"version"];
            currentVersion = [currentVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
            if (currentVersion.length == 2) {
                currentVersion  = [currentVersion stringByAppendingString:@"0"];
            } else if (currentVersion.length == 1){
                currentVersion  = [currentVersion stringByAppendingString:@"00"];
            }
            appStoreVersion = [appStoreVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
            if (appStoreVersion.length == 2) {
                appStoreVersion  = [appStoreVersion stringByAppendingString:@"0"];
            } else if (appStoreVersion.length == 1){
                appStoreVersion  = [appStoreVersion stringByAppendingString:@"00"];
            }
            if([currentVersion floatValue] < [appStoreVersion floatValue]) {
                NSLog(@"【4】判断结果：当前版本号%@ < 商店版本号%@ 需要更新\n=========我是分割线========",[[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"],appInfoDic[@"results"][0][@"version"]);
                block(currentVersion,appInfoDic[@"results"][0][@"version"],appInfoDic[@"results"][0][@"trackViewUrl"],YES);
            } else {
                NSLog(@"【4】判断结果：当前版本号%@ > 商店版本号%@ 不需要更新\n========我是分割线========",[[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"],appInfoDic[@"results"][0][@"version"]);
                block(currentVersion,appInfoDic[@"results"][0][@"version"],appInfoDic[@"results"][0][@"trackViewUrl"],NO);
            }
        });
    }];
    [task resume];
}

+ (NSString *)yyr_contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52:
            // R as RIFF for WEBP
            if ([data length] < 12) {
                return nil;
            }

            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }

            return nil;
    }
    return nil;
}

@end
